<template>
    <el-button type="primary" class="get_code_btn" @click="getCode(formRef as FormInstance)" :disabled="time > 0">
        {{ time > 0 ? `${time}秒后重新获取验证码` : "获取验证码" }}
    </el-button>
</template>

<script setup lang="ts">
import { ref } from "vue";
import type { FormInstance } from "element-plus";
import { reqCode } from "@/api/code";
import type { CodeType } from "@/api/code/type";
import { ElMessage } from "element-plus";
interface Props {
    email: string;
    type: CodeType;
    formRef?: FormInstance;
}
const props = defineProps<Props>();
// 获取验证码
// 验证码倒计时
const time = ref<number>(0);
function countDown() {
    time.value = 60;
    const timer = setInterval(() => {
        time.value--;
        if (time.value <= 0) {
            clearInterval(timer);
        }
    }, 1000);
}
const getCode = async ($FormEl: FormInstance) => {
    // 如果有传入表单对象才进行校验
    if ($FormEl) {
        // 判断邮箱是否符合要求
        try {
            await $FormEl.validateField("email");
        } catch (error) {
            return ElMessage.error("邮箱格式不符合要求");
        }
    }
    // 符合要求后发起请求获取验证码
    const result = await reqCode({
        email: props.email,
        type: props.type,
    });
    // 请求成功时的操作
    if (result.code === 200) {
        ElMessage.success("验证码已发送至邮箱");
        // 开始倒计时
        countDown();
    } else {
        ElMessage.error(result.data);
    }
};
</script>

<style lang="scss" scoped></style>
